package com.lezhi.socialgram.api.sys;

import com.lezhi.socialgram.enums.ResultEnum;
import com.lezhi.socialgram.exception.SocialGramException;
import com.lezhi.socialgram.mapper.sys.SellPackageMapper;
import com.lezhi.socialgram.mapper.sys.TelNumSignInMapper;
import com.lezhi.socialgram.model.sys.OrderInfo;
import com.lezhi.socialgram.model.sys.Pay;
import com.lezhi.socialgram.model.sys.SellPackage;
import com.lezhi.socialgram.model.sys.TelNumSignInUser;
import com.lezhi.socialgram.service.sys.OrderService;
import com.lezhi.socialgram.util.*;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.PingppException;
import com.pingplusplus.model.Charge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by daizhen on 2017/5/8.
 */
@RestController
public class AccountApi {

    private static final Logger logger = LoggerFactory.getLogger(AccountApi.class);

    @Autowired
    SellPackageMapper sellPackageMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    TelNumSignInMapper telNumSignInMapper;

    @Autowired
    OrderService orderService;

    @GetMapping("/getSellPackages")
    public Result getSellPackages() {
        try {
            List<SellPackage> sellPackages = sellPackageMapper.querySellPackageList();
            return ResultUtils.success(sellPackages);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @PostMapping("/payRequire")
    public Result payRequire(@RequestBody @Valid Pay pay, BindingResult bindingResult) {
        ValidUtils.valid(logger, bindingResult);
        try {
            int sellPackageId = pay.getSellPackageId();
            String channel = pay.getChannel();
            String client_ip = XUtil.getRemoteAddr(request);
            String order_no = PrimaryGenerater.getInstance().generaterNextOrderNumber();
            String telNum = pay.getTelNum();

            String indexByTel = XUtil.getTableNameIndexByTel(telNum);
            String table = Param.T_USER_TEL_NUM_INDEX_TABLE_PREFIX + indexByTel;
            TelNumSignInUser telNumSignInUser = new TelNumSignInUser();
            telNumSignInUser.setTelNum(telNum);
            telNumSignInUser.setTable(table);
            TelNumSignInUser userIndex = telNumSignInMapper.getUserId(telNumSignInUser);
            if (userIndex == null)
                return ResultUtils.error(ResultEnum.AUTH_FAILED);
            SellPackage sellPackage = sellPackageMapper.querySellPackageById(sellPackageId);
            int payAmount = sellPackage.getPayAmount();
            int payAmountInCent = payAmount * 100;

            Pingpp.apiKey = "sk_live_DMq2yeP00YtWtfakEy5N86NG";        //sk_live_DMq2yeP00YtWtfakEy5N86NG
            //sk_test_8yXHGCn5er5SeHWbPCf1ebDS
            Map<String, Object> chargeMap = new HashMap<String, Object>();
            //某些渠道需要添加extra参数，具体参数详见接口文档
            chargeMap.put("amount", payAmountInCent);
            chargeMap.put("currency", "cny");
            chargeMap.put("subject", "金豆充值");
            chargeMap.put("body", "Your Body");
            chargeMap.put("order_no", order_no);
            chargeMap.put("channel", channel);
            chargeMap.put("client_ip", client_ip);
            Map<String, String> app = new HashMap<String, String>();
            app.put("id", "app_GSiPiPyT0GKOHCCm");
            chargeMap.put("app", app);

            if ("alipay_wap".equalsIgnoreCase(channel)) {
                Map extra = new HashMap();
                extra.put("success_url", "http://118.190.116.198:9099/pay/success.html");
                extra.put("cancel_url", "http://118.190.116.198:9099/pay/cancel.html");
                extra.put("app_pay", true);
                chargeMap.put("extra", extra);
            }

            try {
                //发起交易请求

                Charge charge = Charge.create(chargeMap);

                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setPayAmount(payAmount);
                orderInfo.setSellPackageId(sellPackageId);
                orderInfo.setChannel(channel);
                orderInfo.setChargeId(charge.getId());
                orderInfo.setOrderNo(order_no);
                orderInfo.setOrderStatus(OrderInfo.ORDER_STATUS_IN_PROGRESS);
                orderInfo.setTelNum(telNum);

                orderService.addOrder(orderInfo);
                return ResultUtils.success(charge);
            } catch (PingppException e) {
                logger.error(e.getMessage());
                throw new SocialGramException(ResultEnum.PAY_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }


}
